package com.ym.b2b.commons.util;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

public class CheckData {

    private final static SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");

    public CheckData() {
    }

    /**
     * 将字符串转位日期类型
     * 
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    public static Date toDateFromFormate(String sdate, String formater) throws ParseException {

        SimpleDateFormat f = new SimpleDateFormat(formater);
        return f.parse(sdate);

    }

    public static String returnDate(Date sdate) {

        if (sdate != null) {
            return dateFormater.format(sdate);
        } else {
            return null;
        }
    }

    public static String checkString(String start) {
        String end = null;
        if (start == null) return "";
        int length = start.length();
        int sub = start.indexOf("'");
        if (sub == -1) end = start;
        else if (length == sub) end = (new StringBuilder(String.valueOf(start))).append("'").toString();
        else end = (new StringBuilder(String.valueOf(start.substring(0, sub + 1)))).append("'").append(checkString(start.substring(sub + 1,
                                                                                                                                   length))).toString();
        return end;
    }

    /***
     * 判断是否为中文
     * 
     * @param str
     * @return
     */
    public static boolean isCn(String str) {

        if (str == null || str.equals("")) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5]+$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;

        }
        return true;
    }

    /***
     * 判断是否为数字
     * 
     * @param str
     * @return
     */
    public static boolean isNumer(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /***
     * 判断是否为字母
     * 
     * @param str
     * @return
     */
    public static boolean isLetters(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
        Pattern pattern = Pattern.compile("[a-zA-Z]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /****************** 时间转换 ********************/
    public static String getDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");// 设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间
        return date;
    }

    public static String getfDate(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);// 设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间
        return date;
    }

    public static Date getDate(String reqDate) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
            Date date = df.parse(reqDate);
            return date;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public static Date getDate(String reqDate, String dateType) {
        try {

            if (reqDate != null && !reqDate.equals("")) {
                SimpleDateFormat df = new SimpleDateFormat(dateType);
                Date date = df.parse(reqDate);
                // System.out.println("format data:"+df.format(date));
                return date;
            } else {
                return null;
            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    /****************** 数据类型转换 ********************/
    public static Long getLong(String str) {
        if (str != null && !str.equals("")) {
            return Long.parseLong(str);
        } else {
            return null;
        }
    }

    public static Integer getInteger(String str) {
        if (str != null && !str.equals("")) {
            return Integer.parseInt(str);
        } else {
            return null;
        }
    }

    public static String getDouble(Double dob) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(dob);
    }

    /**
     * 获取客户端IP
     * 
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String utf8Togb2312(String str) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            switch (c) {
                case '+':
                    sb.append(' ');
                    break;
                case '%':
                    try {
                        sb.append((char) Integer.parseInt(str.substring(i + 1, i + 3), 16));
                    } catch (NumberFormatException e) {
                        throw new IllegalArgumentException();
                    }
                    i += 2;
                    break;
                default:
                    sb.append(c);
                    break;
            }
        }
        // Undo conversion to external encoding
        String result = sb.toString();
        String res = null;
        try {
            byte[] inputBytes = result.getBytes("8859_1");
            res = new String(inputBytes, "UTF-8");
        } catch (Exception e) {
        }
        return res;
    }

    /*** 是否在这个时间之前 **/
    public static boolean isDateBefore(Date date2) {
        try {
            Date date1 = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            return date1.before(date2);
        } catch (Exception e) {
            System.out.print(e.getMessage());
            return false;
        }

    }

    public static boolean isDateAfter(String date2) {
        try {
            Date date1 = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            return date1.after(df.parse(date2));
        } catch (ParseException e) {
            System.out.print(e.getMessage());
            return false;
        }
    }

    /**
     * 验证邮箱
     * 
     * @Title: checkEmail
     * @Description: TODO
     * @Param @param email
     * @Param @return
     * @Return boolean
     * @Throws
     */
    public static boolean checkEmail(String email) {
        if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
            return false;
        } else {
            return true;
        }
    }

    public static void main(String arg[]) throws ParseException {
        String str = "2014-09-09";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.parse(str);
        // CheckData.getDate(str, "yyyy-mm-dd");

    }

    public String checkSearchAreaCode(String areaCode) {

        if ("0".equals(areaCode)) {
            areaCode = "";
        } else {
            String str1 = areaCode;
            for (int i = areaCode.length() - 1; i > 0; i--) {
                int lastIndex = str1.lastIndexOf("0");
                if (lastIndex == i) {
                    str1 = str1.substring(0, str1.length() - 1);
                } else {
                    break;
                }
            }
            int length = str1.length();
            if (length % 2 == 1) {
                str1 = str1 + "0";
            }
            areaCode = str1;
        }
        return areaCode;
    }

}
